<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="shortcut icon" href="">
    <title>Spring</title>
    <style type="text/css">
        body {
            background-color: #eccc68;
        }

        canvas {
            width: 400px;
            height: 300px;
            border: 1px solid black;
        }
    </style>
</head>

<body>
    <h1>Spring</h1>
    <script type="module">
        import {createCanvas, vector2, animation, mouse, curve, circle, fill} from './spring/board.js'
        import {Particle, Spring} from './spring/object.js'

        let springs = [], particles = []
        let spacing = 100
        let gravity = vector2(0, 0.1)
        for (let i = 0; i < 5; ++i) {
            particles.push(new Particle(200, 10 + i * spacing))
            if (i !== 0) {
                springs.push(new Spring(particles[i - 1], particles[i], spacing))
            }
        }
        particles[0].locked = true
        // particles[particles.length - 1].locked = true

        createCanvas()
        function draw() {
            springs.forEach(spring => {
                spring.show()
                spring.update()
            })
            let vertices = []
            particles.forEach(particle => {
                particle.applyForce(gravity)
                particle.update()
                // particle.show()
                vertices.push(particle.position)
                if (mouse.isPress && mouse.position.clone().sub(particle.position).length < 50) {
                    particle.velocity.mul(0)
                    let pointerDiff = mouse.position.clone().sub(particle.position)

                    const targetX = mouse.position.x + pointerDiff.x;
                    const targetY = mouse.position.y + pointerDiff.y;
                    const strength = 0.090159;
                    particle.velocity.x += (targetX - particle.position.x) * strength;
                    particle.velocity.y += (targetY - particle.position.y) * strength;
                    particle.velocity.mul(0.99);
                } else {
                    particle.pointer = false
                }
            })
            curve(vertices)

            if (mouse.isPress) {
                circle(mouse.position.x, mouse.position.y, 50)
                fill('rgba(0, 0, 100, 0.09)')
                // springs[springs.length - 1].b.position = mouse.position.clone()
            }

        }
        animation(draw)
    </script>
</body>

</html>